import 'package:demo/common/widgets/state/state_model.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';

import '../state/state_widget.dart';
import 'page_ctrl.dart';

/// 分页组件，包含缺省页，下拉刷新，todo 预加载
class PageWidget<T> extends StatelessWidget {
  final Widget Function(List<T> list) child;

  final PageCtrl<T> pageCtrl;

  ///是否启用下拉刷新
  final bool enableRefresh;

  ///是否启用上拉
  final bool enableLoadMore;

  final Widget Function(StateModel)? buildLoading;
  final Widget Function(StateModel)? buildEmpty;
  final Widget Function(StateModel, VoidCallback? onTapRetry)? buildError;

  const PageWidget({
    super.key,
    required this.child,
    required this.pageCtrl,
    this.enableRefresh = true,
    this.enableLoadMore = true,
    this.buildLoading,
    this.buildEmpty,
    this.buildError,
  });

  @override
  Widget build(BuildContext context) {
    return StateWidget(
      ctrl: pageCtrl.stateCtrl,
      buildLoading: buildLoading,
      buildEmpty: buildEmpty,
      buildError: buildError,
      child: EasyRefresh(
        controller: pageCtrl.refreshCtrl,
        onRefresh: enableRefresh ? pageCtrl.refresh : null,
        onLoad: enableLoadMore ? pageCtrl.loadMore : null,
        child: ValueListenableBuilder(
          valueListenable: pageCtrl.list,
          builder: (context, state, _) {
            return child(state);
          },
        ),
      ),
    );
  }
}
